package com.cheng.user.service.impl;

import com.cheng.dubbo.api.user.DemoUserService;
import com.cheng.dubbo.api.user.vo.DemoUserLoginVO;
import com.cheng.user.dao.DemoUserDAO;
import com.cheng.user.entity.DemoUser;
import com.cheng.user.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;


@Slf4j
@DubboService
public class DemoUserServiceImpl implements DemoUserService {

    @Autowired
    private DemoUserDAO demoUserDAO;

    private volatile int userID = 1;

    /**
     * 直接加锁了，防止线程不安全，就不考虑性能了
     * @param userLoginVO
     * @return
     */
    @Override
    public synchronized String userLogin(DemoUserLoginVO userLoginVO) {
        DemoUser demoUser = new DemoUser();
        BeanUtils.copyProperties(userLoginVO, demoUser);
        demoUser.setId(1);
        demoUser.setName("用户：" + userID);
        userID++;

        demoUserDAO.login(demoUser);

        String token = JwtUtil.createToken(demoUser.getId());

        return token;
    }

    @Override
    public boolean userTokenCheck(String token) {
        Integer integer = JwtUtil.checkToken(token);
        if (integer == null || integer.equals(0)) {
            log.error("用户token过期");
            return false;
        }

        DemoUser demoUser = demoUserDAO.getDemoUser(integer);
        String a = "用户检查token: " + demoUser.toString();
        log.info(a);

        return true;
    }
}
